package cn.jhc.db;

import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.jhc.bean.ShopCar;


public class ShopCarDao {

	private DataSource dataSource = null;
	
	public ShopCarDao(DataSource dataSource){
		this.dataSource = dataSource;
	}
	
	public void DropCar(ShopCar shopCar) throws SQLException{
		QueryRunner runner = new QueryRunner(dataSource);
		String sql = "drop table shopcar";
		runner.update(sql);
		}
	public void addCar(ShopCar shopCar) throws SQLException{
		QueryRunner runner = new QueryRunner(dataSource);
		String sql = "insert into shopcar(goodname,price,discount,quantity,total,img,goodbn)values(?,?,?,?,?,?,?)";
		runner.insert(sql, new BeanHandler<>(ShopCar.class),shopCar.getGoodname(),shopCar.getPrice(),shopCar.getDisount(),shopCar.getQuantity(),shopCar.getTotal(),shopCar.getImg(),shopCar.getGoodbn());
	}
	
	public void delectAll() throws SQLException{
		QueryRunner runner = new QueryRunner(dataSource);
		runner.update("delete from shopcar");
	}
	
	public List<ShopCar> findAll(){
		List<ShopCar> list = null;
		QueryRunner runner = new QueryRunner(dataSource);
		String sql ="select  * from shopcar";
		ResultSetHandler<List<ShopCar>> h = new BeanListHandler<>(ShopCar.class);
		try {
			list = runner.query(sql, h);
		} catch (SQLException e) {
			// TODO Auto-generated catch block


			e.printStackTrace();
		}
		return list;
	}
	public boolean selectbyname(ShopCar shopCar) {
		boolean a=false;
		QueryRunner runner = new QueryRunner(dataSource);
		String selectsql = "select goodname from shopcar where goodname='"+shopCar.getGoodname()+"'";
		try {
			String name = (String)runner.query(selectsql, new ScalarHandler<>());
			if (name ==null) {
				a= true;
			}
			else {
				a= false;
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return a;
		
	
		
	}
}
